<template>
  <ElDrawer v-model="opened" :title="formType">
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" ref="formRef" label-width="100" :rules="rules" :disabled="isView">
      <ElFormItem label="菜单名称" prop="name">
        <ElInput placeholder="请输入" v-model="form.name" />
      </ElFormItem>
      <ElFormItem label="绑定权限" prop="menuId">
        <!-- <ElInput placeholder="请输入" v-model="form.menuId" /> -->
        <ElTreeSelect
          v-model="form.menuId"
          :data="menuTree"
          node-key="id"
          :filter-node-method="filterNode"
          :props="defaultProps"
          filterable
          check-strictly />
      </ElFormItem>
      <ElFormItem label="图标" prop="icon">
        <IconPicker v-model="form.icon" />
      </ElFormItem>
      <ElFormItem label="封面图片">
        <UploadImg v-model:image-url="form.img" :api="uploadCover" :file-size="5">
          <template #tip>头像最大为 5M</template>
        </UploadImg>
      </ElFormItem>
      <ElFormItem label="访问路径" prop="url">
        <ElInput placeholder="请输入" v-model="form.url" />
      </ElFormItem>
      <ElFormItem label="是否同域">
        <ElSwitch v-model="form.sameDomain" active-text="是" active-value="1" inactive-text="否" inactive-value="0" />
      </ElFormItem>
      <ElFormItem label="排序">
        <ElInputNumber v-model="form.sortOrder" class="mx-4" :min="0" :max="999" controls-position="right" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton v-if="isView" @click="onCancelClicked">关闭</ElButton>
      <ElButton v-else @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, unref, computed, onMounted } from 'vue'
import IconPicker from '@/components/IconPicker/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { FormType } from '@/enums'
import { App } from '@api/uc/app/interface'
import { checkExist, getApp, addApp, updateApp } from '@api/uc/app'
import { uiUpload } from '@api/upload'
import UploadImg from '@/components/Upload/Img.vue'
import { treeMenuOption } from '@api/uc/menu'
import { TreeNode } from '@/api/interface'
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<App.Form>>({})
const opened = ref(false)
const loading = ref(true)
const emit = defineEmits(['success'])
const menuTree = ref<TreeNode[]>([])
const defaultProps = {
  children: 'children',
  label: 'name'
}
onMounted(async () => {
  const { data } = await treeMenuOption()
  menuTree.value = data
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.includes(value)
}

// 重复校验
function validate(query: App.CheckQuery, callback: any) {
  checkExist(query).then(resp => {
    if (resp.data) {
      callback(new Error('输入内容已存在'))
    } else {
      callback()
    }
  })
}

// 名称校验
const validateName = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  const { id, name } = unref(form)
  validate({ id, name }, callback)
}

const rules = reactive<FormRules>({
  menuId: [{ required: true, message: '请绑定权限菜单', trigger: 'blur' }],
  name: [
    { required: true, message: '菜单名称不能为空', trigger: 'blur' },
    { max: 50, message: '菜单名称最大长度 50', trigger: 'blur' },
    { validator: validateName, trigger: 'blur' }
  ],
  url: [{ max: 255, message: '访问地址最大长度 255', trigger: 'blur' }],
  icon: [{ max: 255, message: '图标最大长度 255', trigger: 'blur' }]
})

// 上传封面
function uploadCover(formData: FormData) {
  return uiUpload('app', formData)
}

// 打开表单
async function open(type: FormType, id?: string) {
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    loading.value = false
    form.value = {}
  } else {
    try {
      const { data } = await getApp(id!)
      loading.value = false
      form.value = data
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

// 关闭表单
function close() {
  loading.value = true
  opened.value = false
}

// 保存按钮
function onSaveClicked() {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const menu = Object.assign({}, unref(form))
    if (isAdd.value) {
      addApp(menu).then(() => {
        success()
        sendSuccess()
        close()
      })
    } else {
      updateApp(menu).then(() => {
        success()
        sendSuccess()
        close()
      })
    }
  })
}

// 成功弹出提示
function success() {
  ElMessage({
    type: 'success',
    message: `成功!`
  })
}

// 成功失败弹出提示
// function error(err: string) {
//   ElMessage({
//     type: 'error',
//     message: `失败!  ${err}`
//   })
// }

// 取消按钮
function onCancelClicked() {
  close()
}

// 保存成功发送成功事件
function sendSuccess() {
  emit('success')
}

defineExpose({
  open,
  close
})
</script>
